# -*- coding: utf-8 -*-
import numpy as np
import gauge
import wrf_output
# import matplotlib.pyplot as plt
import os


def wipeOff_max_min(arr):
    """calculate mean except for min and max
    """
    max_arr = np.max(arr)
    min_arr = np.min(arr)
    if max_arr != min_arr:
        arr[np.logical_and(arr == max_arr, arr == min_arr)] = np.nan
    return arr


def Decumulation(seq):
    result = [seq[i + 1] - seq[i] for i in range(len(seq) - 1)]
    result.insert(0, seq[0])
    return result


def get_hourly_band_mean(path, domain, startTime, endTime):
    # domains = ['01', '02']
    # get every mp_cu group wrf_output and extract the center value
    mp = ['2', '6', '7']
    cu = ['0', '1', '2', '7']
    pbl = ['2', '6', '9']
    split_path = path.split('/')
    gridSpacing = split_path[-1]
    gauge_loc = ''
    # scenario = ''
    if gridSpacing == '139':
        # scenario = r'Scenario 1'
        gauge_loc = r'F:/research/rainfall_estimation/dat/Gauge/Gauge_row_col_1.csv'
    elif gridSpacing == '51545':
        # scenario = r'Scenario 2'
        gauge_loc = r'F:/research/rainfall_estimation/dat/Gauge/Gauge_row_col_5.csv'
    elif gridSpacing == '103090':
        # scenario = r'Scenario 3'
        gauge_loc = r'F:/research/rainfall_estimation/dat/Gauge/Gauge_row_col_10.csv'
    results = []
    for i in mp:
        for j in cu:
            for k in pbl:
                mp_cu_pbl = i + j + k
                if os.path.exists(path + '/' + mp_cu_pbl ):
                    input_path = path + '/' + mp_cu_pbl + '/wrfout_d' + domain + '_' + startTime
                    all_gauges = wrf_output.GetAll(input_path, gauge_loc)
                    all_gauges_filter = np.array(
                        list(map(wipeOff_max_min, all_gauges)))
                    mean = np.mean(all_gauges_filter, axis=1)
                    mean = Decumulation(mean)
                    results.append(mean)
    results = np.asarray(results)
    min = np.min(results, axis=0)
    max = np.max(results, axis=0)
    band = [min, max]
    # band_mean = np.mean(band, axis=0)

    # get the mean gauge value
    gauges_mean = gauge.Get50GaugeMean(startTime, endTime)
    return band, gauges_mean


if __name__ == "__main__":
    print("get hourly uncertainty band and mean of gauges")
